const upyun = require('./node-sdk-master/dist/upyun.min.js');

const service = new upyun.Service('file-open-chihe-so', 'fileopen', 'fileopen');

const client = new upyun.Client(service);

const path = require('path')

const ROOT_PATH = path.resolve(__dirname);

const fs = require('fs'); // 引入fs模块

const dir = `${ROOT_PATH}/dist`;

const upyunDir = '/open-static';

const cssDir = `static/css`;

const jsDir = `static/js`;

const imgDir = `static/img`;

// 
let getFileName = (file) => {
	return new Promise((resolve, reject) => {
		let arr = []
		fs.readdir(`${dir}/${file}`, (err, files) => {
			if (!err) {
				files.forEach((filename) => {
					arr.push({
						upyunFile: `${upyunDir}/${file}/${filename}`,
						localFile: `${dir}/${file}/${filename}`
					})
				})
				resolve(arr)
			} else {
				reject(err)
			}
		})
	})
}
// 
let uploadFile = (localFile, upyunFile) => {
	return new Promise((resolve, reject) => {
		let type = (fileurl) => {
			return new Promise((resolve) => {
				// console.log(fileurl)
				fs.stat(fileurl, (eror, stats) => {
					if (eror) {
						console.warn('获取文件stats失败');
					} else {
						resolve(stats.isFile())
					}
				})
			})
		}
		fs.readdir(localFile, async (err, files) => {
			if (!err) {
				let arr = []
				for (let i = 0; i < files.length; i++) {
					if (!/^\./.test(files[i])) {
						let a = await type(`${localFile}/${files[i]}`)
						if (a) {
							arr.push({
								localFile: `${localFile}/${files[i]}`,
								uploadFile: `${upyunFile}/${files[i]}`
							})
						}
					}
				}
				for (let i = 0; i < arr.length; i++) {
					fs.readFile(arr[i].localFile, async (err, bytesRead) => {
						if (!err) {
							let res = await client.putFile(arr[i].uploadFile, bytesRead)
							console.log(res)
						} else {
						}
					})
				}
				resolve('success')
			} else {
				reject(err)
			}

		})
	})
}

// 上传文件夹下，非文件的文件

(async () => {
	//  又拍云地址和本地地址
	//  css的
	let cssFileArr = await getFileName(cssDir)
	// js
	let jsFileArr = await getFileName(jsDir)
	// img
	let imgFileArr = await getFileName(imgDir)
	// 
	let all = [...cssFileArr, ...jsFileArr, ...imgFileArr]


	for (let i = 0; i < all.length; i++) {
		fs.readFile(all[i].localFile, async (err, bytesRead) => {
			if (!err) {
				let res = await client.putFile(all[i].upyunFile, bytesRead)
			} else {
				// console.log(err)
			}
		})
	}

	let type = (fileurl) => {
		return new Promise((resolve, reject) => {
			// console.log(fileurl)
			fs.stat(fileurl, (eror, stats) => {
				if (eror) {
					console.warn('获取文件stats失败');
					reject(eror)
				} else {
					resolve(stats.isFile())
				}
			})
		})
	}
	// 上传dist目录非文件夹的目录
	await uploadFile(dir, upyunDir)

	// 上传static目录下非文件夹的目录
	await uploadFile(`${dir}/static`, `${upyunDir}/static`)

	let res = await client.listDir(`${upyunDir}/static/js`)
	console.log('success')


})();

